#version 120 

// particle data textures
uniform sampler2D positions;
uniform sampler2D velocities;
uniform sampler2D infos;


uniform vec3 randomSeed;

float rand (vec2 n){
  return fract(sin(dot(n.xy, randomSeed.xy))* randomSeed.z);
}

void main(){

	vec3 newPos = texture2D (positions, gl_TexCoord[0].xy).xyz;
	vec3 newVel = texture2D (velocities, gl_TexCoord[0].xy).xyz;
	vec3 newInf = texture2D (infos, gl_TexCoord[0].xy).xyz;
	
	// only emit if slot empty
	if (newInf.x==0) {
	
		// calculate point on sphere
		float theta = rand(gl_TexCoord[0].xy)*3.1417;
		float phi = rand(gl_TexCoord[0].xy+vec2(1000,0))*2*3.1417 - 3.1417;
		float r = 20; //rand(gl_TexCoord[0].xy+vec2(200,0))*50;
		
		float x = r*sin(theta)*cos(phi);
		float y = r*sin(theta)*sin(phi);
		float z = r*cos(phi);
		
		// position on sphere
		newPos = vec3(x,y,z);
		
		// radial initial speed impulse
		newVel = 0.4*vec3(x,y,z);
		
		// set lifetime
		float lifeTime = 3; //rand(gl_TexCoord[0].xy+vec2(300,0))*3;
		newInf = vec3(lifeTime,0,0);
	}
	
	gl_FragData[0] = vec4(newPos,1);
	gl_FragData[1] = vec4(newVel,1);	// no initial velocity
	gl_FragData[2] = vec4(newInf,1);    // lifetime 1 second
}